<template>
	<div>
		<view>
			<uv-calendars :insert="true" ref="calendars" mode="multiple" :date="data" :startDate="startDate"
				@change="chenconfirm" />
		</view>
		<div class="quabbao">
			<div class="sjkuang">
				<div>时段设置<text style="font-size: 16px; color: #707070;">(共{{ dayCount }}天可约)</text></div>
			</div>
			<div class="yuyue" v-for="(notice,ind) in arrives" :key="notice.sid">
				<view>
					<div style="font-size: 18px;">{{ notice.nian }}年{{ notice.yuefen }}月{{ notice.rhao }}号
						({{ notice.zhoji }})</div>
				</view>
				<div class="shuipjuz" v-for="(addtime, sijin) in notice.addtimes" :key="addtime.id">
					<div class="portal">
						<picker mode="time" :value="addtime.time" start="00:00" end="23:59"
							@change="bindTimeChange(notice.sid,addtime.id,sijin, $event)">
							<view class="uni-input" style="font-size: 17px;">{{addtime.time}}</view>
						</picker>
					</div>
					<div class="separator">~</div>
					<div class="portal">
						<picker mode="time" :value="addtime.time1" start="00:00" end="23:59"
							@change="bindTimeChange1(notice.sid,addtime.id,sijin, $event)">
							<view class="uni-input" style="font-size: 17px;">{{addtime.time1}}</view>
						</picker>
					</div>
					<div class="lajit-wrapper">
						<img src="/static/ljt.png" @click="shancushijian(notice.sid,addtime.id,addtime.scid)"
							class="lajit" />
					</div>
					<view class="kaiqi">
						<!-- <switch checked color="#00aa00" style="margin-left: 16px;" @change="switch1Change" /> -->
						<uv-switch v-model="addtime.isActive" activeColor="#00aa00" asyncChange
							@change="() => asyncChange(notice.sid,addtime.id,sijin)"></uv-switch>
					</view>
				</div>
				<div class="tianjiasj" @click="addTimeSlot(ind,notice.addtimes.length)">
					+ 添加时段
				</div>
			</div>
		</div>
		<div style="height: 50px;"></div>
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog cancelText="取消" confirmText="确定" title="温馨提示" :content="nrtsk" @confirm="dialogConfirm"
				@close="dialogClose"></uni-popup-dialog>
		</uni-popup>
		<div class="zaitoyj">
			<div class="bubaoc" @click="bubaocsj">
				不保存,返回
			</div>
			<div class="bubaoc" @click="baocsjsuj">
				保存时间设置
			</div>
		</div>
	</div>
</template>

<script setup>
	import {
		ref,
		computed
	} from 'vue'; // 确保导入的路径与你的项目结构相匹配
	import {
		gonavigateTo
	} from '@/request/wx.js';
	import {
		addition,
		shower,
		shower1,
		del
	} from '@/request/api.js';
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app';

	const arrives = ref([]);
	// {
	// 	sid: 1,
	// 	id: 1,
	// 	nian: 2024,
	// 	yuefen: 11,
	// 	rhao: 7,
	// 	zhoji: '周四',
	// 	isStaff: true,
	// 	addtimes: [{
	// 		id: 1,
	// 		data: "2024-11-7",
	// 		time: '09:00',
	// 		time1: '11:59',
	// 		isActive: true
	// 	}, {
	// 		id: 2,
	// 		data: "2024-11-7",
	// 		time: '14:00',
	// 		time1: '17:59',
	// 		isActive: true
	// 	}]
	// }

	const addtimes = ref([]);

	const nrtsk = ref('');

	const startDate = ref(new Date().toISOString().split('T')[0]);

	const data = ref([]); //"2024-11-7"

	const alertDialog = ref(null);

	const tianshu = ref([]); //"2024-11-7"

	const dayCount = computed(() => tianshu.value.length);

	const calendars = ref(null);

	const delid = ref({});

	const isActive = ref(true);

	let delallid = '';
	let queddel = 0;

	// const time = ref('10:00');

	// const time1 = ref('10:59');

	const token = uni.getStorageSync('uid');
	console.log(token);

	//显示时间设置
	onLoad(async (e) => {
		try {
			const ggb = {
				'sid': token
			};
			const response = await shower(ggb);

			console.log(response)
			const datsi = response.data.data;
			let yyy = '';
			const xxx = [];
			// 使用for...of循环代替forEach
			// for (let i = 0; i < datsi.length; i++) {
			// for (const item of datsi) {
			for (const [index, item] of datsi.entries()) {
				// console.log('ID:', index + 1);
				console.log('ID:', item);
				console.log('ID:', item.date);
				let str = item.date;

				// 截取前4个字符
				let firstPart = str.slice(0, 4); // "2024"

				// 截取第5个字符到第6个字符
				let secondPart = str.slice(5, 7); // "11"

				// 截取第7个字符到最后
				let thirdPart = str.slice(8); // "07"
				let date = new Date(str);
				let weekDay = date.getDay();
				let weekDays = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
				let weekDayText = weekDays[weekDay];
				yyy += item.date

				let obj = {
					sid: index + 1,
					nian: firstPart,
					yuefen: secondPart,
					rhao: thirdPart,
					zhoji: weekDayText,
					isStaff: true,
					addtimes: []
				}
				xxx.push(obj);
				let ooo = [];
				// let opi = [];
				const respi = await shower1({
					sid: item.id
				});
				console.log(respi.data.data.length);
				for (const [index, item] of respi.data.data.entries()) {
					console.log(item);
					let objj = {
						id: index + 1,
						scid: item.id,
						data: str,
						time: item.time,
						time1: item.time1,
						isActive: true
					}
					ooo.push(objj);
					// opi.value = objj.scid;
					if (respi.data.data.length === index + 1) {
						console.log("数组最后一个")
						obj.addtimes = ooo
						console.log('After push:', ooo);
						ooo = [];
					}
				}
			}
			// console.log(xxx)
			// console.log(yyy)
			const dates = yyy.match(/(\d{4}-\d{2}-\d{2})/g) || [];
			data.value = dates;
			tianshu.value = dates;
			arrives.value = xxx;
		} catch (error) {
			console.error("请求失败:", error);
		}
	})

	// shower({
	// 	'sid': token,
	// }).then((res) => {
	// 	console.log(res)
	// })

	const shancushijian = (aid, id, scid) => {
		console.log(scid)
		delid.value = {
			aid: aid,
			id: id
		};
		queddel = scid;
		nrtsk.value = "是否要删除该时间段?";
		alertDialog.value.open();
	}

	const addTimeSlot = (ind, hhh) => {
		console.log(hhh)
		let i = hhh + 1;
		const newTimeSlot = {
			id: i, // 假设id是自增的
			data: arrives.value[ind].nian + "-" + arrives.value[ind].yuefen + "-" + arrives.value[ind].rhao,
			time: '10:00',
			time1: '10:59',
			isActive: true
		};
		console.log(newTimeSlot.id);
		arrives.value[ind].addtimes.push(newTimeSlot);
		console.log(arrives.value[ind].addtimes)
	};

	// const confirm = (e) => {
	// 	console.log(e);
	// };

	// function bindTimeChange(sid, id, sijin, e) {
	// 	console.log(e.detail.value);
	// 	// 首先找到 sid 对应的 arrives 数组元素
	// 	const arriveWithSid = arrives.value.find(arrive => arrive.sid === sid);

	// 	if (arriveWithSid) {
	// 		// 然后找到该元素的 addtimes 数组中 id 对应的元素
	// 		const timeSlot = arriveWithSid.addtimes.find(timeSlot => timeSlot.id === id);

	// 		if (timeSlot) {
	// 			// 更新该元素的 time 属性
	// 			timeSlot.time = e.detail.value;
	// 		} else {
	// 			console.error('未找到对应的时间槽');
	// 		}
	// 	} else {
	// 		console.error('未找到对应的 arrives 元素');
	// 	}
	// }

	// function bindTimeChange1(sid, id, sijin, e) {
	// 	console.log(sid + " : " + id);
	// 	console.log(e.detail.value);
	// 	// 首先找到 sid 对应的 arrives 数组元素
	// 	const arriveWithSid = arrives.value.find(arrive => arrive.sid === sid);

	// 	if (arriveWithSid) {
	// 		// 然后找到该元素的 addtimes 数组中 id 对应的元素
	// 		const timeSlot = arriveWithSid.addtimes.find(timeSlot => timeSlot.id === id);

	// 		if (timeSlot) {
	// 			// 更新该元素的 time 属性
	// 			timeSlot.time1 = e.detail.value;
	// 		} else {
	// 			console.error('未找到对应的时间槽');
	// 		}
	// 	} else {
	// 		console.error('未找到对应的 arrives 元素');
	// 	}
	// }

	// 比较时间的函数
	function compareTime(time1, time2) {
		const [h1, m1] = time1.split(':').map(Number);
		const [h2, m2] = time2.split(':').map(Number);
		return (h1 * 60 + m1) - (h2 * 60 + m2);
	}

	function bindTimeChange(sid, id, sijin, e) {
		console.log(e.detail.value);
		const arriveWithSid = arrives.value.find(arrive => arrive.sid === sid);

		if (arriveWithSid) {
			const timeSlot = arriveWithSid.addtimes.find(timeSlot => timeSlot.id === id);

			if (timeSlot) {
				// 检查新设置的开始时间是否大于结束时间
				if (compareTime(e.detail.value, timeSlot.time1) >= 0) {
					console.error('开始时间不能大于等于结束时间');
					nrtsk.value = "开始时间不能大于等于结束时间";
					alertDialog.value.open();
					return;
				}
				timeSlot.time = e.detail.value;
			} else {
				console.error('未找到对应的时间槽');
			}
		} else {
			console.error('未找到对应的 arrives 元素');
		}
	}

	function bindTimeChange1(sid, id, sijin, e) {
		console.log(sid + " : " + id);
		console.log(e.detail.value);
		const arriveWithSid = arrives.value.find(arrive => arrive.sid === sid);

		if (arriveWithSid) {
			const timeSlot = arriveWithSid.addtimes.find(timeSlot => timeSlot.id === id);

			if (timeSlot) {
				// 检查新设置的结束时间是否小于开始时间
				if (compareTime(timeSlot.time, e.detail.value) >= 0) {
					console.error('结束时间不能小于等于开始时间');
					nrtsk.value = "结束时间不能小于等于开始时间";
					alertDialog.value.open();
					return;
				}
				timeSlot.time1 = e.detail.value;
			} else {
				console.error('未找到对应的时间槽');
			}
		} else {
			console.error('未找到对应的 arrives 元素');
		}
	}

	const chenconfirm = (e) => {
		// 将日期字符串转换为日期对象
		const dateObj = new Date(e.fulldate);
		if (!isNaN(dateObj.getTime())) {
			const year = dateObj.getFullYear();
			const month = dateObj.getMonth() + 1;
			const day = dateObj.getDate();
			const dateKey = `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`;

			// 查找日期是否已存在
			const existingIndex = arrives.value.findIndex(arr => {
				return `${arr.nian}-${arr.yuefen.toString().padStart(2, '0')}-${arr.rhao.toString().padStart(2, '0')}` ===
					dateKey;
			});

			// 查找日期天数是否已存在
			const existingIndex1 = tianshu.value.findIndex(date => date === e.fulldate);

			if (existingIndex !== -1) {
				// 如果存在，则移除对应的时间安排
				addtimes.value = addtimes.value.filter(time => time.date !== e.fulldate);
				// 移除对应的日期
				arrives.value.splice(existingIndex, 1);
				// 减少天数
				tianshu.value.splice(existingIndex1, 1);
			} else {
				const newSid = arrives.value.length + 1;
				// console.log(arrives.value.length)
				// 添加新的日期
				arrives.value.push({
					sid: newSid,
					// id: Date.now(),
					nian: year,
					yuefen: month.toString().padStart(2, '0'),
					rhao: day.toString().padStart(2, '0'),
					zhoji: '周' + '日一二三四五六' [dateObj.getDay()],
					isStaff: true,
					addtimes: [{
						id: 1,
						data: e.fulldate,
						time: '09:00',
						time1: '11:59',
						isActive: true
					}, {
						id: 2,
						data: e.fulldate,
						time: '14:00',
						time1: '17:59',
						isActive: true
					}]
				});
				// 增加天数
				tianshu.value.push(e.fulldate);
			}
			// 对 arrives 数组进行排序
			arrives.value.sort((a, b) => {
				const dateA = new Date(`${a.nian}-${a.yuefen}-${a.rhao}`);
				const dateB = new Date(`${b.nian}-${b.yuefen}-${b.rhao}`);
				return dateA - dateB;
			});
		}
	};

	function asyncChange(sid, id, index) {
		console.log(index);
		// 获取当前时间段的 isActive 状态
		const flse = arrives.value.find(arrive => arrive.sid === sid).addtimes[index].isActive;

		// 如果当前时间段是活跃的，显示模态框询问用户是否要停止预约
		if (flse) {
			uni.showModal({
				content: '是否要停止该时间段的预约？停止后，已有预约记录仍将保留',
				success: (res) => {
					if (res.confirm) {
						// 用户确认停止预约，更新 isActive 状态为 false
						arrives.value.find(arrive => arrive.sid === sid).addtimes[index].isActive = false;
					}
				}
			});
		} else {
			// 如果当前时间段不是活跃的，直接设置 isActive 状态为 true
			arrives.value.find(arrive => arrive.sid === sid).addtimes[index].isActive = true;
		}
		console.log(flse);
	}

	const dialogConfirm = () => {
		console.log('点击确认' + delid.value);
		console.log(delid.value.id + "  ：" + delid.value.aid);
		delallid += queddel + ",";
		// 首先找到 sid 等于 delid.value.valueaid 的 arrives 数组元素
		const arriveWithSid1 = arrives.value.find(arrive => arrive.sid === delid.value.aid);

		if (arriveWithSid1) {
			// 然后找到该元素的 addtimes 数组中 id 等于 delid.value.id 的元素的索引
			const indexToRemove = arriveWithSid1.addtimes.findIndex(timeSlot => timeSlot.id === delid.value.id);

			if (indexToRemove !== -1) {
				// 如果找到了，从 addtimes 数组中删除该元素
				arriveWithSid1.addtimes.splice(indexToRemove, 1);
			}
		}
	};

	const dialogClose = () => {
		console.log(`点击取消`);
		alertDialog.value.close();
	};

	const bubaocsj = () => { //不保存，返回
		gonavigateTo(`/pages/home/index/settings`);
	}

	const baocsjsuj = () => { //保存时间设置
		console.log("保存时间设置");
		console.log(delallid);
		// console.log(token.value);
		// console.log(arrives.value)
		let scshuj = delallid;
		let quanbsj = arrives.value;
		addition({
			'sid': 2,
			'map': quanbsj
		}).then((res) => {
			console.log(res)
		})

		del({
			'id': scshuj
		}).then((res) => {
			console.log(res)
		})
		uni.navigateBack({
			delta: 1 // 返回的页面数，如果 delta 大于现有页面数，则返回到首页
		});
	}
</script>

<style scoped>
	.sjkuang {
		border: 1px solid #e8e8e8;
		/* 边框颜色和宽度 */
		padding: 15px;
		/* 内边距 */
		width: 91%;
		/* 宽度 */
		text-align: center;
		/* 文本居中 */
		font-size: 20px;
		/* 字体大小 */
		background-color: #f5f5f5;
		margin-top: 15px;
	}

	.quabbao {
		padding: 10px;
	}

	.yuyue {
		border: 1px solid #d2d2d2;
		/* 边框颜色和宽度 */
		padding: 20px;
		/* 内边距 */
		width: 88%;
		/* 宽度 */
		text-align: center;
		/* 文本居中 */
		font-size: 16px;
		/* 字体大小 */
		background-color: #f5f5f5;
		/* 背景颜色 */
		border-radius: 10px;
		/* 圆角半径 */
		/* font-weight: bold; /* 字体加粗 */
		margin-top: 15px;
	}

	.shuipjuz {
		display: table;
		margin-top: 25px;
		margin-left: 15px;
	}

	.portal,
	.separator,
	.lajit,
	.kaiqi {
		display: table-cell;
		vertical-align: middle;
	}

	.separator {
		text-align: center;
		width: 10px;
		/* 或者你希望的任何宽度 */
		padding-left: 5px;
		/* 左边距 */
		padding-right: 5px;
		/* 右边距 */
		vertical-align: top;
	}

	.lajit-wrapper {
		margin: 6px 16px;
	}

	.lajit {
		width: 23px;
		height: 23px;
	}

	.kaiqi {
		/* margin-left: 20px; */
	}

	.portal {
		border: 1px solid #cbcbcb;
		/* 边框颜色和宽度 */
		padding: 5px;
		/* 内边距 */
		margin: 10px;
		/* 外边距 */
		width: 66px;
		/* 宽度 */
		height: 20px;
		/* 高度 */
		background-color: #ffffff;
		/* 背景颜色 */
	}

	.tianjiasj {
		color: #1c9399;
		font-size: 18px;
		margin-top: 30px;
		margin-right: 100px;
	}

	/* .zaitoyj {
		width: 100%;
	} */

	.zaitoyj {
		position: fixed;
		bottom: 0;
		width: 100%;
		height: 120rpx;
		display: flex;
		justify-content: space-around;
		background-color: #fff;
		/* padding: 10px 0; */
		box-shadow: 0 -1px 5px rgba(85, 0, 0, 0.1);
	}

	.bubaoc {
		flex: 1;
		background-color: #1c9399;
		transition: background-color 0.3s;
		display: flex;
		justify-content: center;
		align-items: center;
		color: #fff;
	}

	.bubaoc:first-child {
		background-color: #f64b4d;
	}
</style>